package warthog.cradle;

import java.io.*;
import java.util.*;

/**
 * 
 * This class is to deal consistently with the basic issues of producing
 * a file of Java code. Therefore, we have slots for all the basic bits
 * of information needed, including the path to the directory where the
 * file should be written out. (Not the filename; this is derived.)
 * 
 * The idea is to supply a builder-pattern, so that the options can be
 * supplied in any order. 
 * 
 * @author Ian
 *
 */
public class JavaClass {
	public File folder;
	
	public boolean isPublic, isAbstract, isFinal;
	public String packageName, className, baseClass;
	public List<String> interfaces = new ArrayList<String>();
	
	public StringBuilder preamble = new StringBuilder();
	public StringBuilder code = new StringBuilder();
	
	/**
	 * @param path the file upon which the class under construction is based.
	 */
	public JavaClass(File path) {
		folder = path.getParentFile();
		String fileName = path.getName();
		className = fileName.substring(0, fileName.lastIndexOf('.'));
	}
	
	public File javaFile() { return new File(folder, className+".java"); }
	
	public void writeFile() throws IOException {
		Writer w=new FileWriter(javaFile());
		w.write("package "+packageName+";\n");
		w.append(preamble);
		if (isPublic) w.write("public ");
		if (isAbstract) w.write("abstract ");
		if (isFinal) w.write("final ");
		w.write("class "+className);
		if (null != baseClass) w.write(" extends "+baseClass);
		if (!interfaces.isEmpty()) {
			w.write(" implements ");
			boolean comma = false;
			for (String face:interfaces) {
				if (comma) w.write(", ");
				comma=true;
				w.write(face);
			}
		}
		w.write(" {\n");
		w.append(code);
		w.write("}\n");
		w.close();
	}
	
	final static String NL = System.getProperty("line.separator");
	
	public void code(String s) { code.append(s); }
	public void codeln() { code(NL); }
	public void codeln(String s) { code(s); codeln(); }
	public void code(Integer[] a) {
		code("{");
		for (Integer i:a) { code(null==i?"   0,":String.format("%4d,", i)); }
		code("}");
	}
	public void code(int[] a) {
		code("{");
		for (int i:a)  {
			code(String.format("%d,", i));
		}
		code("}");
	}
}
